#!/bin/sh
# This regression test is a part of SIPp.
# A TLS handshake that arrives in small pieces, as over a slow network,
# completes: each wait that brings more of it is progress, not a retry.
. "`dirname "$0"`/../functions"; init

"`get_sipp`" -v | grep -q TLS || skip "no TLS"
command -v openssl >/dev/null || skip "no openssl"

dir=`mktemp -d`
openssl req -x509 -newkey rsa:2048 -nodes -keyout "$dir/key.pem" \
    -out "$dir/cert.pem" -days 1 -subj /CN=sipp >/dev/null 2>&1 ||
    skip "no certificate"
tls="-t l1 -tls_cert $dir/cert.pem -tls_key $dir/key.pem"

sippbg -sn uas $tls -i 127.0.0.1 -p 5073 -m 1

# A proxy passing the server's bytes to the client 16 at a time.
perl -e '
    use IO::Socket::INET; use Socket qw(IPPROTO_TCP TCP_NODELAY);
    use Time::HiRes qw(usleep);
    my $l = IO::Socket::INET->new(LocalAddr => "127.0.0.1:5072", Listen => 1, ReuseAddr => 1) or die;
    alarm 20;
    my $c = $l->accept() or die;
    my $s = IO::Socket::INET->new(PeerAddr => "127.0.0.1:5073") or die;
    setsockopt($_, IPPROTO_TCP, TCP_NODELAY, 1) for ($c, $s);
    my ($from, $to, $piece) = fork() ? ($c, $s, 65536) : ($s, $c, 16);
    while (sysread($from, my $d, 65536)) {
        for (my $i = 0; $i < length $d; $i += $piece) {
            syswrite($to, substr($d, $i, $piece));
            usleep(2000) if $piece < 65536;
        }
    }
    shutdown($to, 2);' &
sleep 1

sippfg -sn uac $tls -i 127.0.0.1 -p 5070 -m 1 127.0.0.1:5072 >/dev/null 2>&1
status=$?
rm -rf "$dir"

if test $status -eq 0; then
    ok
else
    fail "the call failed with $status"
fi
